import { useWebConfigStore, useRefs } from "@/stores"
export const initAd = () => {
	const webConfigStore = useWebConfigStore();
	const { WEBCONFIG } = useRefs(webConfigStore);
	let rewardedVideoAd : any, interstitialAd : any;
	if(WEBCONFIG.value){
		// #ifdef MP-WEIXIN
		if (wx.createRewardedVideoAd && WEBCONFIG.value.weixin_incentive_status=='1') {
			rewardedVideoAd = wx.createRewardedVideoAd({
				adUnitId: WEBCONFIG.value.weixin_incentive_ad_id
			})
		}
		if (wx.createInterstitialAd && WEBCONFIG.value.weixin_interstitial_status=='1') {
			interstitialAd = wx.createInterstitialAd({
				adUnitId: WEBCONFIG.value.weixin_interstitial_ad_id
			})
		}
		// #endif
		// #ifdef MP-TOUTIAO
		if (tt.createRewardedVideoAd && WEBCONFIG.value.douyin_incentive_status=='1') {
			rewardedVideoAd = tt.createRewardedVideoAd({
				adUnitId: WEBCONFIG.value.douyin_incentive_ad_id
			})
		}
		if (tt.createInterstitialAd && WEBCONFIG.value.douyin_interstitial_status=='1') {
			interstitialAd = tt.createInterstitialAd({
				adUnitId: WEBCONFIG.value.douyin_interstitial_ad_id
			})
		}
		// #endif
		if (rewardedVideoAd) {
			rewardedVideoAd.onError((err : any) => {
				console.log(err)
			})
		}
		if (interstitialAd) {
			interstitialAd.onLoad(() => {
				console.log('插屏广告加载中')
			})
			interstitialAd.onError((err : any) => {
				console.log('加载错误', err)
			})
			interstitialAd.onClose(() => { })
		}
	}
	
	const show = () => {
		return new Promise((resolve, reject) => {
			if (rewardedVideoAd) {
				rewardedVideoAd.onClose((status : any) => {
					console.log('关闭', status)
					resolve(status);
				})
				rewardedVideoAd.onError((err : any) => {
					reject();
					console.log(err)
				})
				rewardedVideoAd.show().catch(() => {
					rewardedVideoAd.load()
						.then(() => rewardedVideoAd.show())
						.catch((err : any) => {
							reject();
							console.log('激励视频 广告显示失败', err)
						})
				})
			} else {
				reject();
			}
		})
	}
	const showInterstitial = () => {
		return new Promise((resolve, reject) => {
			if (interstitialAd) {
				interstitialAd.onClose((status : any) => {
					console.log('关闭', status)
					resolve(status);
				})
				interstitialAd.onError((err : any) => {
					reject();
					console.log(err)
				})
				interstitialAd.show().catch(() => {
					interstitialAd.load()
						.then(() => interstitialAd.show())
						.catch((err : any) => {
							reject();
							console.log('插屏视频 广告显示失败', err)
						})
				})
			} else {
				reject();
			}
		})
	}
	return {
		show,
		showInterstitial
	}
}